﻿using BodaNetCommunications.Cores;
using BodaNetCommunications.McComs;
using BodaNetCommunications.Utilities.ComTypes;
using BodaNetCommunications.Utilities.Results;

namespace BodaNetCommunications.CIPComs
{
    public class CipCommService : CommReadWrite, ICipCommService
    {
        public ConnectionOptions Options { get; private set; }

        public bool IsConnected => _commDevice != null && _commDevice.IsConnected;

        private Cip _commDevice;

        public CipCommService()
        {
                
        }

        public BodaResult Connect(ConnectionOptions connectionOptions)
        {
            if (IsConnected)
            {
                _byteTransform.EndianType = _byteTransform.EndianType = EndianType.CDAB; 


                BodaResult bodaResult = new BodaResult();
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"Cip【{Options.Ip}:{Options.Port}】的连接已经在线，不需要重复连接";
                return bodaResult;
            }

            Options = connectionOptions;
            base._byteTransform = new ByteTransformBase();
            _commDevice = new Cip();

            _byteTransform.EndianType = _byteTransform.EndianType = EndianType.ABCD;

            return _commDevice.Connect(Options);
        }

        public void Disconnect()
        {
            _commDevice?.Disconnect();
        }

        public void Dispose()
        {
            Disconnect();
        }


        /// <summary>
        /// 重写基础数据的读取功能
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="length">数据个数</param>
        /// <returns></returns>
        public override BodaResult<byte[]> Read(string address, ushort length)
        {
            BodaResult<byte[]>? readResult = _commDevice.Read(address, length);
            return readResult;
        }

        public BodaResult<byte> ReceiveMsg(int timeout = 2000, int bytesLen = 1024)
        {
            throw new NotImplementedException();
        }

        public BodaResult SendMsgc(byte[] bytes, int timeout = 1500)
        {
            throw new NotImplementedException();
        }
    }
}
